package com.ruoyi.merchant.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.merchant.domain.Category;
import com.ruoyi.merchant.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类管理Controller
 */
@RestController
@RequestMapping("/merchant/category")
public class CategoryController extends BaseController {

    @Autowired
    private ICategoryService categoryService;

    /**
     * 查询分类列表（树形结构）
     */
    @GetMapping("/list")
    public AjaxResult list(Category category) {
        List<Category> list = categoryService.selectCategoryList(category);
        return success(categoryService.buildCategoryTree(list));
    }

    /**
     * 获取分类下拉树列表
     */
    @GetMapping("/tree")
    public AjaxResult tree() {
        Category category = new Category();
        category.setStatus(1); // 只查询启用的分类
        List<Category> list = categoryService.selectCategoryList(category);
        return success(categoryService.buildCategoryTree(list));
    }

    /**
     * 获取分类详细信息
     */
    @GetMapping(value = "/{categoryId}")
    public AjaxResult getInfo(@PathVariable("categoryId") Long categoryId) {
        return success(categoryService.selectCategoryByCategoryId(categoryId));
    }

    /**
     * 新增分类
     */
    @Log(title = "分类管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody Category category) {
        int result = categoryService.insertCategory(category);
        if (result > 0) {
            // 重新查询获取完整数据
            Category savedCategory = categoryService.selectCategoryByCategoryId(category.getCategoryId());
            return success(savedCategory);
        }
        return error("新增分类失败");
    }

    /**
     * 修改分类
     */
    @Log(title = "分类管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody Category category) {
        return toAjax(categoryService.updateCategory(category));
    }

    /**
     * 删除分类
     */
    @Log(title = "分类管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{categoryIds}")
    public AjaxResult remove(@PathVariable Long[] categoryIds) {
        return toAjax(categoryService.deleteCategoryByCategoryIds(categoryIds));
    }
}
